package com.borderbears.backend.connection;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;

import javax.swing.tree.TreeModel;

import nanoxml.XMLElement;
import nanoxml.XMLParseException;

import com.borderbears.backend.media.MediaTreeModel;

public class RemoteXMLConnection extends Connection {

	private final Logger log = Logger.getLogger(getClass().getName());

	private final MediaTreeModel treeModel;
	private String url;

	public RemoteXMLConnection(final String name, final String url) {
		super(name);
		this.url = url;
		treeModel = new MediaTreeModel();
	}

	@Override
	public TreeModel getTreeModel() {
		return treeModel;
	}

	@Override
	public void reload() {

	}

	private XMLElement loadXML(final String urlString) {
		// final String urlString = Config.getConfig().get(CONF_MEDIAURL, "");

		try {
			final URL url = new URL(urlString);

			final InputStreamReader isr = new InputStreamReader(url
					.openStream());
			final XMLElement xml = new XMLElement();
			xml.parseFromReader(isr);
			log.info("XML parsed.");
			return xml;
		} catch (final MalformedURLException e) {
			log.warning("URL was malformed: " + urlString);
		} catch (final XMLParseException e) {
			log.warning("Error parsing XML:\n" + e.getMessage());
		} catch (final IOException e) {
			log.warning("Error connecting to: " + urlString);
		}

		return null;

	}

	@Override
	public void deserialize(final XMLElement xml) {
		url = xml.getStringAttribute("url");
		setName(xml.getStringAttribute("name"));
	}

	@Override
	public XMLElement serialize() {
		final XMLElement xml = new XMLElement();
		xml.setName("RemoteXMLConnection");
		xml.setAttribute("url", url.toString());
		xml.setAttribute("name", getName());
		return xml;
	}

}
